<!--
 * @description  : 市管-计划/检查列表
 * @descriptionDetail: 市管-计划/检查列表
 * @copyright    : 浙江烟草
 * @author       : dw
 * @create       : 2022-10-09 22:21:21
-->
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar
		 :is-white="false"
		  :title="navTitle"
		   :custom-back="goBack"
		   style="z-index: 99999"
		   >
			<view class="nav-right-icon" v-if="tabIndex == 0">
				<u-icon name="plus" color="#FFF" @tap="handlerPlanDetail"></u-icon>
			</view>
			<view class="nav-right-icon" v-if="tabIndex == 1">
				<u-icon color="#FFF" name="more-dot-fill" size="38" @click="isOpen = true"></u-icon>
			</view>
		</theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="tabIndex== 0?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<view class="content u-page">
			<view class="tabsBottom" v-show="tabIndex==0">
				<u-sticky>
					<u-cell-group class="sticky-header">
						<u-cell-item icon="calendar" title="开始/结束日期" :value="rangeDate" :arrow="true" @tap="dateRange=true">
						</u-cell-item>
					</u-cell-group>
				</u-sticky>
				<!-- 日计划 上拉加载 -->
				<me-table
				 :i="0"
				  :index="0"
				   :top="100"
				    :load-data="loadPlanData"
				     :init-load="false"
				      ref="mescrollItem0"
				      >
					<template #default="d">
						<view class="card">
							<u-swipe-action
							 :show="d.data.show"
							  :index="d.data.dayUuid"
							   :disabled="d.data.swiperDisabled"
							    @click="swiperClick"
							     @open="swiperOpen"
							     :options="d.data.swiperOption"
							     >
								<day-plan-item :plan="d.data"></day-plan-item>
							</u-swipe-action>
						</view>
					</template>
				</me-table>
			</view>
			<view class="tabsBottom" v-show="tabIndex==1">
				<view style="margin-top: 20rpx;">
					<u-empty margin-top="100" text="没有检查数据" mode="list" v-if="checkList.length == 0"></u-empty>
					<view v-for="(cItem, idx) in checkList" :key="idx">
						<check-item :data="cItem"></check-item>
					</view>
				</view>
			</view>
		</view>
		<u-tabbar :list="list" :active-color="$theme.u_type_primary" icon-size="40" bg-color="#F3F4F5" :mid-button="false" v-model="current" @change="tabsChange"></u-tabbar>
		<u-calendar mode="range" max-date="2099-12-31" v-model="dateRange" @change="handlerSearchDate"></u-calendar>
		<u-calendar mode="date" max-date="2099-12-31" v-model="dateChoiceShow" @change="handlerSearchDay"></u-calendar>
		<!-- 添加操作按钮 -->
		<u-action-sheet :list="addBtnsList" v-model="isOpen" @click="handlerDropMenu"></u-action-sheet>
		<u-popup
		 :mask-close-able="false"
		  v-model="AcceptanceShow"
		   border-radius="20"
		    mode="center"
		     width="80%"
		      height="306rpx"
		      >
			<view class="good-popup-lay">
				<view style="margin: 32rpx 0;">
					<u-form-item label-width="150" label="受理单号:" label-position="left">
						<u-input
						 v-model="applyCode"
						  placeholder="请输入"
						  :needValid="true"
						  ></u-input>
					</u-form-item>
				</view>
				<view class="good-popup-lay__btns">
					<u-button plain type="primary" size="medium" @click="()=>{AcceptanceShow = false;applyCode = '';}">
						取&nbsp;&nbsp;&nbsp;&nbsp;消
					</u-button>
					<u-button type="primary" size="medium" @click="saveAcceptance">
						保&nbsp;&nbsp;&nbsp;&nbsp;存
					</u-button>
				</view>
			</view>
		</u-popup>
		<u-select v-model="isShow" title="选择任务来源" mode="mutil-column-auto" :list="taskSourceList" @confirm="sourceConfirm"></u-select>
	</view>
</template>

<script>
	import meTable from '@/components/me-table.vue';
	import commonService from "@/service/common/common.service.js";
	import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";
	import checkService from "@/service/check/check.service"
	import {
		dateUtils,
	} from "@/common/util"
	import DayPlanItem from './components/day-plan-item.vue';
	import CheckItem from './components/check-item.vue';
	import {
		CHECK_TASK_SUBJECT,
	} from "@/common/common_enum.js";
	import {
		M_CHECK_GROUP,
		M_TASK_SOURCE,
		M_DAY_PLAN_STATUS,
		M_DAY_CHECK_STATUS,
	} from "@/service/check/mapping/enum.js";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			meTable,
			DayPlanItem,
			CheckItem,
			fabButton
		},
		mixins: [MescrollMoreMixin, ],
		data() {
			return {
				M_TASK_SOURCE,
				M_DAY_PLAN_STATUS,
				M_DAY_CHECK_STATUS,
				dateRange: false,
				rangeDate: dateUtils.dateFormat("yyyy-MM-dd", dateUtils.firstDate(new Date())) + "至" + dateUtils.dateFormat("yyyy-MM-dd", dateUtils.lastDate(new Date())),
				startDate: dateUtils.dateFormat("yyyy-MM-dd", dateUtils.firstDate(new Date())),
				endDate: dateUtils.dateFormat("yyyy-MM-dd", dateUtils.lastDate(new Date())),
				nowDay: this.$u.date(Date.now(), 'yyyy-mm-dd'),
				dateChoiceShow: false,
				isOpen: false,
				keyword: "",
				background: {
					background: "#fff",
				},
				backTextStyle: {
					color: "#333333",
				},
				current: 0,
				tabList: [{
					name: "日计划",
					text: "日计划",
				}, {
					name: "检查",
					text: "检查",
				}, ],
				barStyle: {
					// 底部滑块的样式
					background: "#027AFF !important",
					marginBottom: "-5rpx",
					width: "60rpx",
					marginLeft: "-10rpx",
				},
				tabIndex: 0, // 表示当前活动的tab选项
				checkList: [], // 检查列表数据(不分页)
				list: [{
						iconPath: "home",
						selectedIconPath: "home-fill",
						text: '日计划',
						count: 0,
						isDot: false,
						customIcon: false,
					},
					{
						iconPath: "edit-pen",
						selectedIconPath: "edit-pen-fill",
						text: '检查',
						count: 0, // 总数
						isDot: false,
						customIcon: false,
					},
				],
				CHECK_TASK_SUBJECT,
				isAddTemp: false, // 是否可以添加临时任务（当天有重点监管类型的检查户才可添加）
				normalPlanStatus: false, // 是否计划正常中
				addBtnsList: [], // 添加操作按钮
				taskSourceList: [],
				isShow: false, // 是否显示任务来源
				AcceptanceShow: false,
				applyCode: "",
				taskSourceSpecialList: [],
				fContent: [{
					iconPath: require('@/static/add.png'),
					selectedIconPath: require('@/static/add.png'),
					text: '添加计划',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/omore.png'),
					selectedIconPath: require('@/static/omore.png'),
					text: '更多',
					active: false,
				}],
			};
		},
		// 页面加载成功后也要设置一次，用于处理本页面刷新后失效问题
		mounted() {
			this.setRightBtns();
			this.setSourceData();
		},
		onShow() {
			if (this.tabIndex != 0) {
				this.queryCheckData();
			}
		},
		methods: {
			setSourceData() {
				Promise.all([commonService.bscCodesTree('M_TASK_SOURCE'), commonService.bscCodesTree('M_TASK_SOURCE_ITEM'), ]).then(rs => {
					let list = rs[0].data || [];
					let itemlist = rs[1].data || [];
					itemlist.forEach(itx => {
						itx.value = itx.bcbCode;
						itx.label = itx.bcbName;
					});
					list.forEach((item) => {
						if (item.bcbCode == M_TASK_SOURCE.REPORT_COMPLAINT ||
							item.bcbCode == M_TASK_SOURCE.TURN_TO_HOLD_ASSIGN ||
							item.bcbCode == M_TASK_SOURCE.OTHER) {
							let source = {
								value: item.bcbCode,
								label: item.bcbName,
								children: itemlist.filter((sub) => {
									return item.bcbCode == sub.parentBcbCode
								}),
							};
							this.taskSourceList.push(source);
						}
					});
					console.log(this.taskSourceList);
				}).catch(e => {
					console.log(e);
					let list = this.$store.state.dicts['M_TASK_SOURCE'];
					let itemlist = this.$store.state.dicts['M_TASK_SOURCE_ITEM'];
					list.forEach((item) => {
						if (item.value == M_TASK_SOURCE.REPORT_COMPLAINT ||
							item.value == M_TASK_SOURCE.TURN_TO_HOLD_ASSIGN ||
							item.value == M_TASK_SOURCE.OTHER) {
							let source = {
								value: item.value,
								label: item.label,
								children: itemlist.filter((sub) => {
									return item.value == sub.parentBcbCode
								}),
							};
							this.taskSourceList.push(source);
						}
					});
				});
			},
			// 根据页面返回携带的参数刷新列表
			updateBackState(param) {
				if (param.sort) {
					let sortList = param.sort;
					this.$storage.set(this.$rp.check.SORT, {
						sortData: sortList,
						sortDate: this.nowDay,
					});
					this.queryCheckData();
					return;
				}
				// 选中零售户或无证户(添加临时任务)
				let selectRetailers = param['temporaryTask'];
				if (selectRetailers && selectRetailers.add == 'true') {
					this.queryCheckData()
					return;
				}
				// 刷新页面
				param.refresh && (this.tabIndex == 0 ? this.$refs["mescrollItem0"].refresh() : this.queryCheckData());
				this.tabIndex == 0 && this.getMescroll(0).triggerDownScroll();
			},
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.tabIndex == 0 ? "添加计划" : "更多", () => {
					// 添加日计划操作
					if (this.tabIndex == 0) {
						this.handlerPlanDetail({});
					} else {
						this.isOpen = true;
					}
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					if (this.tabIndex == 0) {
						this.handlerPlanDetail({});
					} else {
						this.isOpen = true;
					}
				}
			},
			// 添加日计划
			handlerAddPlan() {
				this.$u.route('/pages/check/addDayPlan');
			},
			// 点击查看计划详情
			handlerPlanDetail(planDetail) {
				this.setRouteParam(planDetail);
				this.handlerAddPlan();
			},
			// 日计划
			loadPlanData(page) {
				return new Promise((resolve, reject) => {
					checkService.partInDayPlanList(page.num, page.size, {
						orgUuid: this.curUser.user.org.orgUuid,
						planDateStart: this.startDate,
						planDateEnd: this.endDate,
						dateRangeS: [], // TODO 这是个啥
						menuCode: null,
					}).then(res => {
						if (res.success) {
							this.updateSwiperOptionByRes(res.data);
							resolve({
								count: res.count,
								data: res.data,
							});
						} else {
							this.$u.toast(res.msg);
							resolve({
								count: 0,
								data: [],
							});
						}
					}).catch(err => {
						this.$u.toast(err);
						resolve({
							count: 0,
							data: [],
						});
					});
				});
			},
			updateSwiperOptionByRes(arr) {
				arr && arr.forEach(itm => {
					itm.show = false;
					itm.swiperDisabled = true;
					itm.swiperOption = [];
					// 草稿状态
					if (itm.status === M_DAY_PLAN_STATUS.DRAFT) {
						itm.swiperDisabled = false;
						itm.swiperOption.push({
							text: '编辑',
							action: 'edit',
							style: {
								backgroundColor: this.$theme.u_type_primary,
							},
						}, {
							text: '删除',
							action: 'del',
							style: {
								backgroundColor: this.$theme.u_type_error,
							},
						}, );
					} else if ((itm.status === M_DAY_PLAN_STATUS.SUBMITTED || itm.status === M_DAY_PLAN_STATUS.HAVING) && itm.terminationFlag == '0') {
						itm.swiperDisabled = false;
						itm.swiperOption.push({
							text: '终止',
							action: 'stop',
							style: {
								backgroundColor: this.$theme.u_type_warning,
							},
						}, );
					}
				});
			},
			swiperClick(index1, index) {
				let datas = this.$refs.mescrollItem0.listDatas;
				let cur = -1;
				for (let i = 0; i < datas.length; i++) {
					if (datas[i].dayUuid == index1) {
						cur = i;
						break;
					}
				}
				if (cur == -1) {
					this.$u.toast("选中数据无效");
					return;
				}
				let opts = datas[cur].swiperOption;
				if (opts[index].action == 'del') {
					this.$modal.confirm('确定要删除吗?', () => {
						checkService.delDayPlan([datas[cur].dayUuid, ]).then((res) => {
							this.$u.toast(res.msg);
							if (res.success) {
								this.$u.toast('删除成功');
								this.getMescroll(0).triggerDownScroll();
							} else {
								this.$u.toast(res.msg);
							}
						}).catch(err => {
							this.$u.toast(err);
						});
					});
				} else if (opts[index].action == 'edit') {
					this.setRouteParam(datas[cur]);
					this.$u.route('/pages/check/addDayPlan');
				} else if (opts[index].action == 'stop') {
					this.$u.route('/pages/check/dayPlanStop?dayUuid=' + datas[cur].dayUuid);
				}
				this.refreshSwiperPlan();
			},
			refreshSwiperPlan() {
				let self = this;
				this.$refs.mescrollItem0.listDatas.map((val, idx) => {
					val.show = false;
					self.$set(val, 'show', false);
					return true;
				});
			},
			swiperOpen(index) {
				this.$refs.mescrollItem0.listDatas.map((val, idx) => {
					this.$refs.mescrollItem0.listDatas[idx].show = index == val.dayUuid;
				});
			},
			updateOrginalSortList(list) {
				let signList = list.filter(ip => {
					return !ip.status && ip.signStatus == '02'; // 如果是已签到
				});
				let ipArr = [];
				signList.forEach(ixp => {
					ipArr.push(ixp.checkUuid);
				});
				let finishList = list.filter(ip => {
					return ip.status == '02'; // 如果是已完成
				});
				finishList.forEach(ixp => {
					ipArr.push(ixp.checkUuid);
				});
				let unSignList = list.filter(ix => {
					return !ipArr.includes(ix.checkUuid);
				});
				return [...signList, ...unSignList, ...finishList, ];
			},
			updateSortList(list) {
				let sortApr = this.$storage.get(this.$rp.check.SORT);
				sortApr = sortApr == "" ? {} : sortApr;
				let sortDate = sortApr.sortDate || '';
				let sortList = sortApr.sortData || [];
				if (sortList.length == 0 || sortDate != this.nowDay) { // 为空或者日期不对的检查列表数据不排序
					return list;
				} else {
					let otherList = list.filter(it => !sortList.includes(it.checkUuid));
					let realList = list.filter(it => sortList.includes(it.checkUuid));
					let rList = [];
					sortList.forEach(itm => {
						for (let i = 0; i < realList.length; i++) {
							if (realList[i].checkUuid == itm) {
								rList.push(realList[i]);
								break;
							}
						}
					});
					rList = [...rList, ...otherList, ];
					let signList = rList.filter(ip => {
						return !ip.status && ip.signStatus == '02'; // 如果是已签到
					});
					let ipArr = [];
					signList.forEach(ixp => {
						ipArr.push(ixp.checkUuid);
					});
					let finishList = rList.filter(ip => {
						return ip.status == '02'; // 如果是已完成
					});
					finishList.forEach(ixp => {
						ipArr.push(ixp.checkUuid);
					});
					let unSignList = rList.filter(ix => {
						return !ipArr.includes(ix.checkUuid);
					});
					rList = [...signList, ...unSignList, ...finishList, ];
					return rList;
				}
			},
			// 检查数据
			queryCheckData() {
				this.isAddTemp = false;
				this.$u.loading("查询中...");
				checkService.queryCheckClientListByCurrentDay({
					currentDate: this.nowDay,
					page: 1,
					limit: 999,
				}).then(dr => {
					this.$u.hideLoading();
					if (dr.success) {
						this.checkList = this.updateSortList(this.updateOrginalSortList(dr.data));
						let unFinishList = dr.data.filter((item) => {
							return item.status != M_DAY_CHECK_STATUS.FINISH
						});
						this.list[1].count = (unFinishList || []).length;
					} else {
						this.checkList = [];
						this.$u.toast(dr.msg);
					}
					this.checkList.forEach(item => {
						if (item.dayPlanStatus == M_DAY_PLAN_STATUS.SUBMITTED || item.dayPlanStatus == M_DAY_PLAN_STATUS.HAVING) {
							this.normalPlanStatus = true;
							return;
						}
					});
					this.checkList.forEach((item) => {
						if (item.groupUuid != M_CHECK_GROUP.RANDOM) { // 32014 改成 04了
							this.isAddTemp = true;
							return;
						}
					});
					this.getBtnList();
				}).catch(e => {
					console.log(e);
					this.checkList = [];
					this.getBtnList();
					this.$u.toast("查询失败");
				});
			},
			getBtnList() {
				this.addBtnsList = [];
				if (this.isAddTemp && this.normalPlanStatus) {
					this.addBtnsList.push({
						text: "添加临时任务",
						index: 0,
					});
				}
				this.addBtnsList.push({
					text: "线路优化",
					index: 3,
				});
			},
			// 切换tabs刷新列表
			tabsChange(curr) {
				this.tabIndex = curr;
				this.setRightBtns();
				this.tabIndex == 0 ? this.$refs["mescrollItem0"].refresh() : this.queryCheckData();
			},
			// 日期区间查询条件
			handlerSearchDate(d) {
				this.startDate = d.startDate;
				this.endDate = d.endDate;
				this.rangeDate = d.startDate + "至" + d.endDate;
				this.$refs["mescrollItem0"].refresh();
			},
			handlerSearchDay(e) {
				this.nowDay = e.result;
				this.queryCheckData();
			},
			checkInfo() {
				if (this.$u.test.isEmpty(this.checkList)) {
					this.$u.toast('请先制定计划');
				} else {
					this.isShow = true;
				}
			},
			// 任务来源确认事件
			sourceConfirm(e) {
				console.log(e);
				this.taskSourceSpecialList = e;
				this.isShow = false;
				if (e[1].value != '04') {
					this.setRouteParam(this.checkList);
					this.$u.route("/pages/check/temporaryTask?isSingle=1&taskSource=" + e[0].value + "&taskSourceItem=" + e[1].value);
				} else {
					this.AcceptanceShow = true;
				}
			},
			saveAcceptance() {
				let e = this.taskSourceSpecialList;
				if (this.$u.test.isEmpty(this.applyCode)) return this.$u.toast('请输入受理单号')
				this.setRouteParam(this.checkList);
				this.$u.route("/pages/check/temporaryTask?isSingle=1&taskSource=" + e[0].value + "&taskSourceItem=" + e[1].value + "&applyCode=" + this.applyCode);
				this.applyCode = "";
				this.AcceptanceShow = false;
			},
			tempTask() {
				if (this.$u.test.isEmpty(this.checkList)) {
					this.$u.toast('请先制定计划');
				} else {
					this.setRouteParam(this.checkList);
				}
			},
			// 导航栏菜单
			handlerDropMenu(type) {
				console.log("点击了" + type);
				this.isOpen = false;
				switch (this.addBtnsList[type].index) {
					case 0:
						// 添加临时走访任务(有证户、无证户)
						this.checkInfo();
						break;
					case 1:
						// 添加12313临时任务
						this.tempTask();
						break;
					case 2:
						// 采集无证户
						this.$u.route("/pages/query/nolicence/add/addNolicence?isAddTempTask=true");
						break;
					case 3:
						this.$modal.alert("未开始或含GIS坐标的检查任务才能参与线路优化", () => {
							this.$u.route({
								url: "/pages/check/lineOptimize",
								params: {
									nowDay: this.nowDay,
								},
							});
						});
						break;
					default:
						break;
				}
			},
			signLocation(geo, type) {
				checkService.workSignIn({
					"personUuid": this.curUser.user.personUuid,
					"signType": type,
					"signLongitude": geo.longitude,
					"signLatitude": geo.latitude,
				}).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						this.$u.toast('打卡成功');
					} else {
						this.$u.toast(res.msg);
					}
				}).catch(e => {
					this.$modal.hideLoading();
				});
			},
			// 检查详情
			handlerCheckDetail(detail) {
				// 根据groupUuid判断是否是32015电子烟客户检查
				if (detail.groupUuid == '32015') {
					this.setRouteParam(detail);
					this.$u.route('/pages/eCigar/eCigarCheckItem');
					return;
				} else {
					// 有证户检查要阅读检查作业指导书，无证户、已完成的检查任务不用阅读
					// if (!detail.isHaveLicense || (detail.status == '2' && detail.isFinish)) {
					if (detail.taskSubject == CHECK_TASK_SUBJECT.noHaveLic || detail.statusName == '已完成') {
						this.setRouteParam(detail);
						this.$u.route('/pages/check/checkDetail');
						return;
					}
					this.setRouteParam(detail);
					this.$u.route('/pages/check/checkGuide?retailerUuid=' + detail.retailerUuid + '&taskSubject=' + detail.taskSubject);
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.page {
		padding: 0;
	}

	.content {
		//background-color: #F3F4F5;
		background-color: #FFF;
	}

	.sticky-header {
		position: fixed;
		/* #ifdef H5-DINGDING  */
		top: 0px;
		/* #endif */
		/* #ifndef H5-DINGDING  */
		top: 45px;
		/* #endif */
		width: 100%;
		z-index: 999;
	}

	.good-popup-lay {
		padding: $cm-content-paddng-row;
		width: 100%;
		height: 100%;

		&__title {
			font-size: 36rpx;
			font-weight: 600;
			color: $u-main-color;
			margin: 10rpx 0;
			text-align: center;
			width: 100%;
		}

		&__btns {
			width: 100%;
			margin-top: 24rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;

			uni-button {
				flex: 0.28;
			}
		}
	}
</style>
